package com.hwy.widget.segment

import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.RectF

/**
 * =======================================
 * 作者: hewenyu
 * 日期: 2022/5/4 13:35
 * 说明: 通用的滑块组件
 * =======================================
 */
class SimpleSegmentSlider(tabSegment: TabSegment) : AbstractSegmentSlider(tabSegment) {

    private val sliderPaint by lazy {
        Paint().apply {
            isAntiAlias = true
            isDither = true
            style = Paint.Style.FILL_AND_STROKE
        }
    }

    /**
     * 滑块绘制的区域
     */
    private val sliderRect by lazy {
        RectF()
    }

    override fun draw(currentIndex: Int, canvas: Canvas) {
        sliderPaint.color = segment.getSliderColor()
        if (isAnimatorRunning()) {
            drawRunningSlider(canvas)
        } else {
            // 绘制静态的滑块
            segment.getRectByIndex(currentIndex)?.run {
                sliderRect.set(this)
                val corner = segment.getSliderCorner()
                canvas.drawRoundRect(sliderRect, corner, corner, sliderPaint)
            }
        }
    }

    /**
     * 绘制运动中的滑块
     */
    private fun drawRunningSlider(canvas: Canvas) {
        segment?.run {
            getRectByIndex(fromIndex)?.let { fromRect ->
                getRectByIndex(toIndex)?.let { toRect ->
                    val fromCenterX = fromRect.left + fromRect.width() / 2F
                    val fromCenterY = fromRect.top + fromRect.height() / 2F
                    val toCenterX = toRect.left + toRect.width() / 2F
                    // 取两个矩形的中心位置的横向差值
                    val distance = toCenterX - fromCenterX
                    // 计算动画过程中的横向偏移量
                    val offset = fraction * distance
                    // 计算缩放
                    val scaleX = (fromRect.width() - toRect.width()) * fraction
                    val scaleY = (fromRect.height() - toRect.height()) * fraction

                    // 计算实际绘制的矩形边界
                    val left = fromCenterX + offset - (fromRect.width() - scaleX) / 2F
                    val top = fromCenterY - (fromRect.height() - scaleY) / 2F
                    val right = fromCenterX + offset + (fromRect.width() - scaleX) / 2F
                    val bottom = fromCenterY + (fromRect.height() - scaleY) / 2F
                    sliderRect.set(left, top, right, bottom)

                    val corner = segment.getSliderCorner()
                    canvas.drawRoundRect(sliderRect, corner, corner, sliderPaint)
                }
            }
        }
    }

}